package com.orcs.leefei.utils.kotlin

import android.content.Context
import android.content.SharedPreferences
import android.os.Build
import android.preference.PreferenceManager

/**
 * Created by FeiLee on 2016/12/26 11:16.
 */

val Context.prefs: SharedPreferences
    get() {
        return PreferenceManager.getDefaultSharedPreferences(this)
    }

fun getPrefs(): SharedPreferences {
    return PreferenceManager.getDefaultSharedPreferences(Orcs.context)
}

fun Context.prefs(name: String, mode: Int = Context.MODE_PRIVATE): SharedPreferences =
        getSharedPreferences(name, mode)

fun SharedPreferences.clear() {
    apply(getEditor().clear())
}

inline fun SharedPreferences.edit(func: SharedPreferences.Editor.() -> Unit) {
    val editor = edit()
    editor.func()
    editor.apply()
}

/*
 * -----------------------------------------------------------------------------
 *  Private methods
 * -----------------------------------------------------------------------------
 */
private fun SharedPreferences.getEditor(): SharedPreferences.Editor {
    return this.edit()
}

private fun SharedPreferences.apply(editor: SharedPreferences.Editor) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
        editor.commit()
    } else {
        editor.apply()
    }
}